package com.kbook.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.kbook.action.Action;
import com.kbook.bean.UserBean;

public abstract class BaseController {
	Action action = null;
	

	/**
	 * 通用控制层，只需要实现initAction和getView方法即可
	 * @param request
	 * @param response
	 * @return
	 * @throws Throwable
	 */
	public ModelAndView control(HttpServletRequest request,HttpServletResponse response) throws Throwable {

		Map<String, Object> model = new HashMap<String, Object>();
		request.setAttribute("model", model);
		
		
		UserBean user = (UserBean)request.getAttribute("user");
		if(user == null){
			user = new UserBean(1l, "游客", "游客", 0);
		}
		user.setAction(getAction());
		
		Map params = (Map)request.getAttribute("params");
		
		Object result = user.excute(params);
		//JSONObject json = JSONObject.fromObject(result);
		//model.put("result", json.toString());
		model.put("result", result);
		model.put("params", params);
		
		return new ModelAndView(getView());
	}


	public Action getAction() {
		initAction();
		return action;
	}
	
	protected void setAction(Action action) {
		this.action = action;
	}


	/**
	 * 初始化执行逻辑操作的action
	 */
	protected abstract void initAction();
	
	
	/**
	 * 返回view页面
	 * @return
	 */
	protected abstract String getView();
	
}
